<?php
declare (strict_types=1);

namespace app\traits;

use app\service\ImageHashService;
use image\image\Exception;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\SnowFlake;
use think\annotation\Route;

/**
 * 文件上传公共方法
 * Trait UploadTrait
 * @package app\traits
 */
trait UploadTrait
{
    /**
     * 图片上传，将图片上传至阿里云oss
     * @Route("upimg", method="POST")
     */
    public function uploadOss(){
        try {
            $files = $_FILES['img'];
        } catch(OssException $e) {
            return json_error(['status'=>1,'message'=>'参数错误']);
        }

        $name = $files['name'];
        //验证器验证上传的文件
        validate(['img' => 'fileSize:10485670|fileExt:jpg,gif,jpeg,png|fileMime:image/jpeg,image/gif,image/png'])->check(request()->file());
        $format = strrchr($name, '.');
        $accessKeyId = config('filesystem.disks.aliyun.accessId');
        $accessKeySecret = config('filesystem.disks.aliyun.accessSecret');
        $endpoint = config('filesystem.disks.aliyun.endpoint');
        $bucket = config('filesystem.disks.aliyun.bucket');

        $object = 'fx/'.sha1(date('YmdHis', time()) . uniqid()) . $format;
        $filePath = $files['tmp_name'];
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            if(!$result){
                return json_error(['message' => '上传失败']);
            }else{
                return json_ok(['message' => '上传成功', 'path' => $result['info']['url']]);
            }
        } catch(OssException $e) {
            return json_error(['message' => '上传失败']);
        }
    }
}